from flask import redirect, url_for, render_template, jsonify, request, flash
from flask_login import current_user, login_required
from app import admin, db, mongo
from app.utils import mongo_operate
from . import bp
from app.models import User, Movies, Tags, Country
from app.utils.page import Paginator
from datetime import datetime
import os
from sqlalchemy.exc import IntegrityError
from sqlalchemy import or_


# 添加一个简单的管理首页路由
@bp.route('/')
@login_required
def index():
    if not current_user.is_authenticated or not current_user.is_admin:
        return redirect(url_for('user.login'))
    count_users = User.query.count()
    pipeline_unique_users = [
        {"$group": {"_id": "$user_id"}},
        {"$count": "unique_user_count"}
    ]
    result = mongo.cx['movies']['browsing_history'].aggregate(pipeline_unique_users)
    activated_user = next(result, {}).get("unique_user_count", 0)
    total_recommends = len(list(mongo_operate.find_documents('score_record', {})))
    total_views = len(list(mongo_operate.find_documents('browsing_history', {})))

    pipeline_daily_counts = [
        {
            "$project": {
                "day": {
                    "$dateToString": {"format": "%Y-%m-%d", "date": "$created_at"}
                }
            }
        },
        {
            "$group": {
                "_id": "$day",
                "count": {"$sum": 1}
            }
        },
        {
            "$sort": {"_id": 1}
        }
    ]
    daily_result = mongo.cx['movies']['browsing_history'].aggregate(pipeline_daily_counts)
    recent = {doc['_id']: doc['count'] for doc in daily_result}

    return render_template('admin/index.html', count_users=count_users, activated_user=activated_user,
                           total_recommends=total_recommends, total_views=total_views,
                           recent_date=list(recent.keys()), recent_data=list(recent.values()),
                           title="仪表盘")


@bp.route('/manage_movies')
@bp.route('/manage_movies/<int:page>')
def manage_movies(page=1):
    name_query = request.args.get('name', '').strip()
    director = request.args.get('director', '').strip()
    query = Movies.query
    if name_query:
        query = query.filter(Movies.name.contains(name_query))
    if director:
        query = query.filter(Movies.director.contains(director))
    movies = query.order_by(Movies.years.desc()).all()
    pagination = Paginator(movies, page=page, per_page=5)
    countries = Country.query.all()
    return render_template('admin/manage_movies.html', title='电影管理', pagination=pagination, countries=countries)

@bp.route('/movie/<int:movie_id>', methods=['GET'])
@login_required
def movie_detail(movie_id):
    movie = Movies.query.filter_by(id=movie_id).first()
    if not movie or movie is None:
        flash("电影不存在", "warning")
        return redirect(url_for('user.index'))
    return render_template('admin/movie_detail.html', title='电影详情', movie=movie)

@bp.route('/add_movie', methods=['POST'])
@login_required
def add_movie():
    name = request.form.get('name')
    director = request.form.get('director')
    country = request.form.get('country')
    years = request.form.get('years')
    leader = request.form.get('leader')
    rate = request.form.get('rate')
    intro = request.form.get('intro')
    image = request.files['image']
    timestamp = int(datetime.now().timestamp() * 1000)

    if image.filename == '':
        return flash("No selected file", "warning")
    filename = f'{timestamp}_{image.filename}'
    image_link = f'upload/{filename}'
    filepath = os.path.join('app/static/upload', filename)
    image.save(filepath)

    movie = Movies(name=name, director=director, country=country, years=years, leader=leader, rate=rate, intro=intro,
                   image_link=image_link)
    try:
        db.session.add(movie)
        db.session.commit()
    except IntegrityError:
        db.session.rollback()
        flash("未知错误, 请稍后再试", "warning")
        return redirect(url_for('admin.manage_movies'))
    return redirect(url_for('admin.manage_movies'))

@bp.route('/delete_movie/<int:movie_id>')
@login_required
def delete_movie(movie_id):
    movie = Movies.query.filter_by(id=movie_id).first()
    if not movie or movie is None:
        flash("电影不存在, 请核对后重试", "warning")
        return jsonify("Movie not found."), 4004
    try:
        db.session.delete(movie)
        db.session.commit()
        flash("删除成功", "success")
    except IntegrityError:
        db.session.rollback()
        flash("未知错误, 请稍后重试", "warning")
    return redirect(url_for('admin.manage_movies'))


@bp.route('/manage_tags')
@bp.route('/manage_tags/<int:page>')
def manage_tags(page=1):
    tags = Tags.query.order_by(Tags.id).all()
    pagination = Paginator(tags, page=page, per_page=10)
    return render_template('admin/manage_tags.html', title="标签管理", pagination=pagination)

@bp.route('/add_tag', methods=['POST'])
@login_required
def add_tag():
    data = request.get_json()
    name = data.get('tagName')
    print(name)
    tag = Tags.query.filter_by(name=name).first()
    if tag:
        flash("该标签已存在, 请核对后重试", "warning")
        return jsonify("Tag is Already"), 400
    tag = Tags(name=name)
    try:
        db.session.add(tag)
        db.session.commit()
        flash("添加成功", "success")
    except IntegrityError:
        db.session.rollback()
        flash("未知错误, 请稍后再试", "warning")
        return jsonify("Unknown error"), 5000
    return jsonify("add tag success"), 200

@bp.route('/edit_tag', methods=['POST'])
@login_required
def edit_tag():
    data = request.get_json()
    editTagName = data.get('editTagName')
    tagName = data.get('tagName')
    tag = Tags.query.filter_by(name=editTagName).first()
    if not tag or tag is None:
        flash("该标签不存在, 请核对后重试", "warning")
        return jsonify("Tag not found."), 400
    tag.name = tagName
    try:
        db.session.add(tag)
        db.session.commit()
        flash("修改成功", "success")
    except IntegrityError:
        db.session.rollback()
        flash("未知错误, 请稍后再试", "warning")
        return jsonify("Unknown error"), 5000
    return jsonify("edit tag success"), 200

@bp.route('/delete_tag/<int:tagId>')
@login_required
def delete_tag(tagId):
    tag = Tags.query.filter_by(id=tagId).first()
    if not tag or tag is None:
        flash("标签不存在, 请核对后重试", "warning")
        return jsonify("Tag is Not Found"), 4004
    try:
        db.session.delete(tag)
        db.session.commit()
        flash("删除成功", "success")
    except IntegrityError:
        db.session.rollback()
        flash("未知错误, 请稍后重试", "warning")
        return jsonify("Unknown error"), 5000
    return jsonify("delete tag success"), 200


@bp.route('/manage_users')
@bp.route('/manage_users/<int:page>')
@login_required
def manage_users(page=1):
    users = User.query.all()
    user_list = [{'id': user.id, 'username': user.username, 'email': user.email, 'is_admin': '是' if user.is_admin else '否',
                  'created_at': user.created_at, 'updated_at': user.updated_at} for user in users]
    pagination = Paginator(user_list, page=page, per_page=10)
    return render_template('admin/manage_users.html', title='用户管理', pagination=pagination)

@bp.route('/add_user', methods=['POST'])
@login_required
def add_user():
    data = request.get_json()
    username = data.get('username')
    email = data.get('email')
    password = data.get('password')
    is_admin = True if data.get('role') == 'admin' else False
    user = User.query.filter(or_(User.username == username, User.email == email)).first()
    print(user)
    if user:
        flash("用户已存在, 请核对后重试", "warning")
        return jsonify("User Already Exist"), 4000
    user = User(username, email, password, is_admin)
    try:
        db.session.add(user)
        db.session.commit()
        flash("添加成功", "success")
    except IntegrityError:
        db.session.rollback()
        flash("未知错误, 请稍后重试", "warning")
        return jsonify("Unknown error"), 5000
    return jsonify("add user success"), 200

@bp.route('/edit_user', methods=['POST'])
@login_required
def edit_user():
    data = request.get_json()
    userId = data.get('userId')
    username = data.get('username')
    email = data.get('email')
    password = data.get('password')
    is_admin = True if data.get('role') == 'admin' else False
    user = User.query.filter_by(id=userId).first()
    if not user:
        flash("用户不存在, 请核对后重试", "warning")
        return jsonify("User Not Found"), 4004
    user.username = username
    user.email = email
    user.password = password
    user.is_admin = is_admin
    try:
        db.session.add(user)
        db.session.commit()
        flash("编辑成功", "success")
    except IntegrityError:
        db.session.rollback()
        flash("未知错误, 请稍后重试", "warning")
        return jsonify("Unknown error"), 5000
    return jsonify("edit user success"), 200

@bp.route('/delete_user/<int:userId>')
@login_required
def delete_user(userId):
    user = User.query.filter_by(id=userId).first()
    if not user:
        flash("用户不存在, 请核对后重试", "warning")
        return jsonify("User Not Found"), 4004
    try:
        db.session.delete(user)
        db.session.commit()
        flash("删除成功", "success")
    except IntegrityError:
        db.session.rollback()
        flash("未知错误, 请稍后重试", "warning")
        return jsonify("Unknown error"), 5000
    return jsonify("delete user success"), 200


@bp.route('/browsing_history')
@bp.route('/browsing_history/<int:page>')
@login_required
def browsing_history(page=1):
    history_list = list(mongo_operate.find_documents('browsing_history', {}, sort=[('created_at', -1)]))
    enrich_mongo_records(history_list)
    pagination = Paginator(history_list, page=page, per_page=15)
    return render_template('admin/browsing_history.html', title='浏览记录', pagination=pagination)


@bp.route('/recommend_result')
@bp.route('/recommend_result/<int:page>')
@login_required
def recommend_result(page=1):
    result_list = list(mongo_operate.find_documents('score_record', {}, sort=[('created_at', -1)]))
    enrich_mongo_records(result_list)
    pagination = Paginator(result_list, page=page, per_page=15)
    return render_template('admin/recommend_result.html', title='推荐记录', pagination=pagination)


@bp.route('/score_record')
@bp.route('/score_record/<int:page>')
@login_required
def score_record(page=1):
    score_list = list(mongo_operate.find_documents('score_record', {}, sort=[('created_at', -1)]))
    enrich_mongo_records(score_list, include_rating=True)
    pagination = Paginator(score_list, page=page, per_page=10)
    return render_template('admin/score_record.html', title='打分记录', pagination=pagination)


def enrich_mongo_records(records, include_rating=False):
    for record in records:
        record['_id'] = str(record.get('_id', ''))
        movie_id = str(record.get('movie_id'))
        user_id = str(record.get('user_id'))

        movie = Movies.query.filter_by(id=movie_id).first()
        user = User.query.filter_by(id=user_id).first()

        record['movie_name'] = movie.name if movie else '[未知电影]'
        record['username'] = user.username if user else '[未知用户]'

        if 'created_at' in record and record['created_at']:
            record['created_at'] = record['created_at'].strftime('%Y-%m-%d %H:%M:%S')
        else:
            record['created_at'] = ''

        if include_rating:
            record['user_rating'] = str(record.get('user_rating', ''))

    return records
